package com.greateffect.littlebud.lib.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import com.greateffect.littlebud.lib.BuildConfig;
import com.greateffect.littlebud.lib.R;
import com.greateffect.littlebud.lib.adapter.CustomDialogCallbackAdapter;
import com.greateffect.littlebud.lib.app.ActivityStackManger;
import com.greateffect.littlebud.lib.cache.CustomExtraKeys;
import com.greateffect.littlebud.lib.di.component.AppComponent;
import com.greateffect.littlebud.lib.dialog.CustomDialogHelper;
import com.greateffect.littlebud.lib.event.DialogDismissEvent;
import com.greateffect.littlebud.lib.leaks.FixHuaWeiMemLeak;
import com.greateffect.littlebud.lib.leaks.IMMLeaks;
import com.greateffect.littlebud.lib.mvp.IPresenter;
import com.greateffect.littlebud.lib.mvp.IViewAdvance;
import com.greateffect.littlebud.lib.ui.BaseActivity;
import com.greateffect.littlebud.lib.utilcode.BarUtils;
import com.greateffect.littlebud.lib.utilcode.ToastUtils;
import com.greateffect.littlebud.lib.utils.JLogUtil;
import com.greateffect.littlebud.lib.utils.KeyboardUtil;
import com.greateffect.littlebud.lib.utils.NetworkUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by ZengCS on 2019/1/8.
 * E-mail:zengcs@vip.qq.com
 * Add:成都市天府软件园E3
 */
public abstract class BaseNormalActivityAdv<P extends IPresenter> extends BaseActivity<P> implements IViewAdvance {
    // private static Toast mToast;
    protected boolean isLoading = false;
    private boolean isFullScreen = false;
    private boolean isKeepScreenOn = false;
    private AlertDialog progressDialog;
    protected boolean isGoToAppSettings = false;
    protected String mAppName;


    @Override
    public void setupActivityComponent(AppComponent appComponent) {

    }

    // 是否透明状态栏
    protected boolean isTransparentStatusBar() {
        return true;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {//优化界面输入框 隐藏体验
            // get current focus,Generally it is EditText
            View view = getCurrentFocus();
            if (KeyboardUtil.isShouldHideSoftKeyBoard(view, ev)) {
                KeyboardUtil.hideSoft(this);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Nullable
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityStackManger.getInstance().addActivity(this);
        IMMLeaks.fixFocusedViewLeak(getApplication());
        mAppName = getString(R.string.app_name);
        // 状态栏透明
        if (isTransparentStatusBar())
            BarUtils.transparentStatusBar(this);
    }

    protected void setToolbarPaddingWhenTransStatusBar() {
        ViewGroup toolbarLayout = findViewById(R.id.id_container_toolbar);
        if (toolbarLayout != null && isTransparentStatusBar())
            toolbarLayout.setPadding(0, BarUtils.getStatusBarHeight(), 0, 0);
    }

    @Override
    public boolean useEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDialogDismissEvent(DialogDismissEvent event) {
        if (isFullScreen) {
            requestFullScreen(null);
        }
    }

    @Override
    public void showLoading() {
        showLoading(getString(R.string.txt_loading_common));
    }

    @Override
    public void hideLoading() {
        isLoading = false;
        if (progressDialog != null)
            progressDialog.dismiss();
        if (isFullScreen)
            requestFullScreen(null);
    }

    @Override
    public void showMessage(String message) {
        hideLoading();
        if (!isFinishing())
            CustomDialogHelper.showCustomMessageDialog(this, message);
    }

    public void showExitMessageDialog(String msg) {
        CustomDialogHelper.DialogParam dialogParam = new CustomDialogHelper.DialogParam();
        dialogParam.setMessage(msg);
        dialogParam.setPositiveBtnText("退出");
        CustomDialogHelper.showCustomMessageDialog(this, dialogParam, new CustomDialogCallbackAdapter() {
            @Override
            public void onConfirm() {
                killMyself();
            }
        });
    }

    @Override
    public void launchActivity(Intent intent) {
        startActivity(intent);
    }

    @Override
    public void launchActivity(Class clz) {
        launchActivity(clz, null);
    }

    @Override
    public void launchActivity(Class clz, String param) {
        Intent intent = new Intent(this, clz);
        if (!TextUtils.isEmpty(param))
            intent.putExtra(CustomExtraKeys.KEY_STRING, param);
        launchActivity(intent);
    }

    @Override
    public boolean isNetworkConnected() {
        return NetworkUtil.isConnected();
    }

    @Override
    public void showLoading(String msg) {
        // 显示Loading框
        if (!isFinishing())
            forceShowLoading(msg);
    }

    @Override
    protected void getDataFromNet() {
    }

    @Override
    public void forceShowLoading(String msg) {
        if (progressDialog == null) {
            View view = LayoutInflater.from(this).inflate(R.layout.dialog_custom_loading, null);
            TextView tips = view.findViewById(R.id.tv_tip);
            tips.setText(msg);

            // progressDialog = new Dialog(this, R.style.CustomDialogWithDim);
            AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.CustomDialogFullScreen);
            builder.setView(view).setCancelable(false);

            progressDialog = builder.show();
            progressDialog.setCanceledOnTouchOutside(false);
        } else {
            TextView tips = progressDialog.findViewById(R.id.tv_tip);
            if (tips != null)
                tips.setText(msg);
        }
        if (!progressDialog.isShowing()) {
            if (!isFinishing())
                progressDialog.show();
        }
    }

    @Override
    public void showToast(String message) {
        if (TextUtils.isEmpty(message)) return;
        ToastUtils.showLong(message);
    }

    @Override
    public void showShortcutMenu() {

    }

    @Override
    public void hideShortcutMenu() {

    }

    @Override
    public void hideSoftInput() {

    }

    @Override
    public Context getAttachedContext() {
        return this;
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    /**
     * 打开应用程序设置界面
     */
    protected void openAppDetailSettings() {
        isGoToAppSettings = true;

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        intent.setData(Uri.fromParts("package", getPackageName(), null));
        startActivity(intent);
    }

    @Override
    public void killMyself() {
        ActivityStackManger.getInstance().finishActivity(this);
    }

    @Override
    protected void onDestroy() {
        hideLoading();
        progressDialog = null;
        super.onDestroy();
        FixHuaWeiMemLeak.fixLeak(this);
        ActivityStackManger.getInstance().removeActivity(this);
//        if (mToast != null)
//            mToast.cancel();
    }

    /**
     * 移除全屏
     */
    protected void removeFullScreen() {
        isFullScreen = false;
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
    }

    /**
     * 全屏
     */
    protected void requestFullScreen(Boolean keepScreenOn) {
        isFullScreen = true;
        if (Build.VERSION.SDK_INT >= 19) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        } else {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(option);
        }
        // 设置常亮
        if (keepScreenOn != null && keepScreenOn)
            setKeepScreenOn();
    }

    /**
     * 清除常亮
     */
    protected void clearKeepScreenOn() {
        JLogUtil.d("clearKeepScreenOn() called");
        try {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            isKeepScreenOn = false;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置屏幕常亮
     */
    protected void setKeepScreenOn() {
        if (BuildConfig.DEBUG) {
            JLogUtil.d("setKeepScreenOn() called，isKeepScreenOn = " + isKeepScreenOn);
        }
        if (isKeepScreenOn) return;
        JLogUtil.d("setKeepScreenOn() called");
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        isKeepScreenOn = true;
    }
}
